package com.jingdun.sport.common.util;

import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.config.Config;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.*;
import com.qiniu.api.url.URLEscape;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.storage.model.FileListing;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

public class QiniuUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(QiniuUtils.class);

    /**
     * 默认上传空间
     */
    public static String QINIU_TEST_BUCKET;
    public static String QINIU_BASE_BUCKET;
    //    public static String QINIU_GOODS_BUCKET;
    public static String QINIU_ICON_BUCKET = "buling-live";
    public static String QINIU_ORDER_BUCKET;
    //    public static String QINIU_ACTIVITYS_BUCKET;
    public static String yougoubao = "buling-live";
    ;
    public static String yougoubaovideo;
    /**
     * 测试空间
     */
    public static String QINIU_TEST_DOMAIN;

    /**
     * 空间默认域名
     */
    public static String QINIU_BASE_DOMAIN;
    /**
     * 商品
     */
    public static String QINIU_GOODS_DOMAIN = "buling.hzleijin.com";

    /**
     * icon
     */
    public static String QINIU_ICON_DOMAIN;

    /**
     * 订单
     */
    public static String QINIU_ORDER_DOMAIN;

    /**
     * 活动
     */
    public static String QINIU_ACTIVITYS_DOMAIN;

    /**
     * 视频
     */
    public static String QINIU_VIDEO_DOMAIN;

    private static Mac mac;

    private static Auth auth;

    private static UploadManager uploadManager;

    private static String LIMIT_SIZE;

    private static String QINIU_MIME;

    public static Configuration configuration;

    public static BucketManager bucketManager;

    public static String HTTP_TYPE = "http://";

    public static String HTTPS_TYPE = "https://";

    public static String ACCESS_KEY = "vE-3LGtCUfdbFXXwNTwUqmCfeUWBw41ZsyEBa8A1";

    public static String SECRET_KEY = "10m_hT4JsKatl85UvczYdbva-4XBSAAiCh9Y5x6C";

    static {
//        Properties properties = PropertiesUtils.load("props/framework.properties");
//
//        QINIU_TEST_BUCKET = properties.getProperty("QINIU_BUCKET_TEST");
//        QINIU_BASE_BUCKET = properties.getProperty("QINIU_BASE_BUCKET");
//        QINIU_GOODS_BUCKET = properties.getProperty("QINIU_GOODS_BUCKET");
        yougoubao = "buling-live";
//        QINIU_ICON_BUCKET = properties.getProperty("QINIU_ICON_BUCKET");
//        QINIU_ORDER_BUCKET = properties.getProperty("QINIU_ORDER_BUCKET");
//        QINIU_ACTIVITYS_BUCKET = properties.getProperty("QINIU_ACTIVITYS_BUCKET");
//        QINIU_VIDEO_BUCKET = properties.getProperty("QINIU_VIDEO_BUCKET");
        yougoubaovideo = "buling-live";
//
//        QINIU_TEST_DOMAIN = properties.getProperty("QINIU_TEST_DOMAIN");
//        QINIU_BASE_DOMAIN = properties.getProperty("QINIU_BASE_DOMAIN");
//        QINIU_GOODS_DOMAIN = properties.getProperty("QINIU_GOODS_DOMAIN");
        QINIU_GOODS_DOMAIN = "buling.hzleijin.com";
        QINIU_VIDEO_DOMAIN = "buling.hzleijin.com";

//        QINIU_ICON_DOMAIN = properties.getProperty("QINIU_ICON_DOMAIN");
//        QINIU_ORDER_DOMAIN = properties.getProperty("QINIU_ORDER_DOMAIN");
//        QINIU_ACTIVITYS_DOMAIN = properties.getProperty("QINIU_ACTIVITYS_DOMAIN");
//        QINIU_VIDEO_DOMAIN = properties.getProperty("QINIU_VIDEO_DOMAIN");
//
//        LIMIT_SIZE = properties.getProperty("LIMIT_SIZE");
//        QINIU_MIME = properties.getProperty("QINIU_MIME");
//        Config.ACCESS_KEY = properties.getProperty("ACCESS_KEY");
//        Config.SECRET_KEY = properties.getProperty("SECRET_KEY");
//        HTTP_TYPE = properties.getProperty("HTTP_TYPE");
//        HTTPS_TYPE = properties.getProperty("HTTPS_TYPE");
        mac = new Mac(ACCESS_KEY, SECRET_KEY);
        auth = Auth.create(mac.accessKey, mac.secretKey);
        configuration = new Configuration(Region.region0());
        bucketManager = new BucketManager(auth, configuration);
        uploadManager = new UploadManager(configuration);
        if (LIMIT_SIZE == null)
            LIMIT_SIZE = "1000";
    }

    public enum QINIU_BUCKET_DOMAIN_ENUM {
        TEST(QiniuUtils.QINIU_TEST_DOMAIN, QiniuUtils.QINIU_TEST_BUCKET),
        BASE(QiniuUtils.QINIU_BASE_DOMAIN, QiniuUtils.QINIU_BASE_BUCKET),
        yougoubao(QiniuUtils.QINIU_GOODS_DOMAIN, QiniuUtils.yougoubao),
        ICON(QiniuUtils.QINIU_ICON_DOMAIN, QiniuUtils.QINIU_ICON_BUCKET),
        ORDER(QiniuUtils.QINIU_ORDER_DOMAIN, QiniuUtils.QINIU_ORDER_BUCKET),
        ACTIVITY(QiniuUtils.QINIU_ACTIVITYS_DOMAIN, QiniuUtils.yougoubao),
        VIDEO(QiniuUtils.QINIU_VIDEO_DOMAIN, QiniuUtils.yougoubaovideo);
        private String domain;
        private String bucket;

        QINIU_BUCKET_DOMAIN_ENUM(String domain, String bucket) {
            this.bucket = bucket;
            this.domain = domain;
        }

        public String getDomain() {
            return domain;
        }

        public void setDomain(String domain) {
            this.domain = domain;
        }

        public String getBucket() {
            return bucket;
        }

        public void setBucket(String bucket) {
            this.bucket = bucket;
        }
    }

    /**
     * 获取上传下载认证对象
     *
     * @param bucketName 请确保该bucket已经存在
     * @return
     */
    public static String getUploadTocken(String bucketName) throws AuthException, JSONException {
        PutPolicy putPolicy = new PutPolicy(bucketName);
        return putPolicy.token(mac);
    }

    /**
     * 获取token
     *
     * @param bucketName
     * @return
     */
    public static String getWebUptoken(String bucketName) {
        // 请确保该bucket已经存在
        Auth auth = Auth.create(Config.ACCESS_KEY, Config.SECRET_KEY);
        return auth.uploadToken(bucketName);
    }

    /**
     * 获得授权对象
     *
     * @return
     */
    public static Auth getAuth() {
        return Auth.create(mac.accessKey, mac.secretKey);
    }

    public static boolean upload(String bucket, String key, String file) throws AuthException, JSONException {
        PutPolicy putPolicy = new PutPolicy(bucket);
        String uptoken = putPolicy.token(mac);
        PutExtra extra = new PutExtra();

        PutRet ret = IoApi.putFile(uptoken, key, file, extra);
        return ret.ok();
    }

    public static String download(String domain, String key) throws EncoderException, AuthException {
        String baseUrl = URLUtils.makeBaseUrl(domain, key);
        GetPolicy getPolicy = new GetPolicy();
        String downloadUrl = getPolicy.makeRequest(baseUrl, mac);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("from qiniu's url is:" + downloadUrl);
        }
        return downloadUrl;
    }

    public static boolean delete(String bucket, String key) {
        RSClient client = new RSClient(mac);
        return client.delete(bucket, key).ok();
    }

    /**
     * 多个key 一起删除
     *
     * @param keys
     */
    public static boolean batchDelete(String bucket, Set<String> keys) {
        if (keys == null || keys.size() == 0) {
            return false;
        }

        RSClient rs = new RSClient(mac);
        List<EntryPath> entries = new ArrayList<EntryPath>();
        for (String key : keys) {
            EntryPath e = new EntryPath();
            e.bucket = bucket;
            e.key = key;
            entries.add(e);
        }
        BatchCallRet bret = rs.batchDelete(entries);
        return bret.ok();
    }


    /**
     * @param @param  inputStream    待上传文件输入流
     * @param @param  bucketName     空间名称
     * @param @param  key            空间内文件的key
     * @param @param  mimeType       文件的MIME类型，可选参数，不传入会自动判断
     * @param @return
     * @param @throws IOException
     * @return String
     * @throws
     * @Description: 七牛图片上传
     */
    public static String uploadFile(InputStream inputStream, String bucketName, String key, String mimeType) throws IOException {
        byte[] byteData = IOUtils.toByteArray(inputStream);
        Response response = uploadManager.put(byteData, key, getUpToken(bucketName), null, mimeType, false);
        inputStream.close();
        return response.bodyString();
    }

    /**
     * @param @param  inputStream    待上传文件输入流
     * @param @param  bucketName     空间名称
     * @param @param  key            空间内文件的key
     * @param @return
     * @param @throws IOException
     * @return String
     * @throws
     * @Description: 七牛图片上传
     */
    public static String uploadFile(InputStream inputStream, QINIU_BUCKET_DOMAIN_ENUM bucket, String key) throws IOException {
        String token = auth.uploadToken(bucket.getBucket());
        byte[] byteData = IOUtils.toByteArray(inputStream);
        Response response = uploadManager.put(byteData, key, token, null, null, false);
        inputStream.close();
        return QiniuUtils.getFileUrl(String.valueOf(response.jsonToMap().get("key")), bucket.getDomain());
    }

    /**
     * @param @param  inputStream    待上传文件输入流
     * @param @param  bucketName     空间名称
     * @param @param  key            空间内文件的key
     * @param @return
     * @param @throws IOException
     * @return String
     * @throws
     * @Description: 七牛图片上传
     */
    public static String uploadFile(InputStream inputStream, QINIU_BUCKET_DOMAIN_ENUM bucket, String key, Boolean isHttps) throws IOException {
        String token = auth.uploadToken(bucket.getBucket());
        byte[] byteData = IOUtils.toByteArray(inputStream);
        Response response = uploadManager.put(byteData, key, token, null, null, false);
        inputStream.close();
        return QiniuUtils.getFileUrl(String.valueOf(response.jsonToMap().get("key")), bucket.getDomain());
    }

    /**
     * @param @param  inputStream    待上传文件输入流
     * @param @param  bucketName     空间名称
     * @param @return
     * @param @throws IOException
     * @return String
     * @throws
     * @Description: 七牛图片上传
     */
    public static String uploadFileSpecBucket(InputStream inputStream, QINIU_BUCKET_DOMAIN_ENUM bucket) throws IOException {
        byte[] byteData = IOUtils.toByteArray(inputStream);
        Response response = uploadManager.put(byteData, null, getUpToken(bucket.getBucket()), null, null, false);
        inputStream.close();
        return QiniuUtils.getFileUrl(String.valueOf(response.jsonToMap().get("key")), bucket.getDomain());
    }

    /**
     * @param @param  inputStream    待上传文件输入流
     * @param @return
     * @param @throws IOException
     * @return String
     * @throws
     * @Description: 七牛图片上传至默认空间
     */
    public static StringMap uploadFile(InputStream inputStream, String bucket) throws IOException {
        byte[] byteData = IOUtils.toByteArray(inputStream);
        Response response = uploadManager.put(byteData, null, getUpToken(bucket), null, null, false);
        inputStream.close();
        return response.jsonToMap();
    }


    /**
     * @param filePath 待上传文件的硬盘路径
     * @param fileName 待上传文件的文件名
     * @param bucket   空间名称
     * @param key      空间内文件的key
     * @param @return
     * @param @throws  IOException
     * @return String
     * @throws
     * @Description: 七牛图片上传
     */
    public static String uploadFile(String filePath, String fileName, QINIU_BUCKET_DOMAIN_ENUM bucket, String key) throws IOException {
        String token = auth.uploadToken(bucket.getBucket());
        InputStream is = new FileInputStream(new File(filePath + fileName));
        byte[] byteData = IOUtils.toByteArray(is);
        Response response = uploadManager.put(byteData, (key == null || "".equals(key)) ? fileName : key, token);
        is.close();
        return QiniuUtils.getFileUrl(String.valueOf(response.jsonToMap().get("key")), bucket.getDomain());
    }

    /**
     * @param filePath   待上传文件的硬盘路径
     * @param fileName   待上传文件的文件名
     * @param bucketName 空间名称
     * @param @return
     * @param @throws    IOException
     * @return String
     * @Description: 七牛图片上传[若没有指定文件的key, 则默认将fileName参数作为文件的key]
     */
    public static String uploadFile(String filePath, String fileName, String bucketName) throws IOException {
        String token = auth.uploadToken(bucketName);
        InputStream is = new FileInputStream(new File(filePath + fileName));
        byte[] byteData = IOUtils.toByteArray(is);
        Response response = uploadManager.put(byteData, fileName, token);
        is.close();
        return response.bodyString();
    }

    /**
     * @param url        网络上一个资源文件的URL
     * @param bucketName 空间名称
     * @param key        空间内文件的key[唯一的]
     * @param @return
     * @return String
     * @throws QiniuException
     * @throws
     * @Description: 提取网络资源并上传到七牛空间里
     */
    public static String fetchToBucket(String url, String bucketName, String key) throws QiniuException {
//        DefaultPutRet putret = bucketManager.fetch(url, bucketName, key);
        return null;
//        return putret.key;
    }

    /**
     * @param url
     * @param bucketName
     * @param @return
     * @param @throws    QiniuException
     * @return String
     * @throws
     * @Description: 提取网络资源并上传到七牛空间里, 不指定key，则默认使用url作为文件的key
     */
    public static String fetchToBucket(String url, String bucketName) throws QiniuException {
        return null;
//        DefaultPutRet putret = bucketManager.fetch(url, bucketName);
//        return putret.key;
    }

    /**
     * @param bucket       源空间名称
     * @param key          源空间里文件的key(唯一的)
     * @param targetBucket 目标空间
     * @param targetKey    目标空间里文件的key(唯一的)
     * @return void
     * @throws QiniuException
     * @throws
     * @Description: 七牛空间内文件复制
     */
    public static void copyFile(String bucket, String key, String targetBucket, String targetKey) throws QiniuException {
        bucketManager.copy(bucket, key, targetBucket, targetKey);
    }

    /**
     * @param bucket       源空间名称
     * @param key          源空间里文件的key(唯一的)
     * @param targetBucket 目标空间
     * @param targetKey    目标空间里文件的key(唯一的)
     * @param @throws      QiniuException
     * @return void
     * @throws
     * @Description: 七牛空间内文件剪切
     */
    public static void moveFile(String bucket, String key, String targetBucket, String targetKey) throws QiniuException {
        bucketManager.move(bucket, key, targetBucket, targetKey);
    }

    /**
     * @param bucket
     * @param key
     * @param targetKey
     * @param @throws   QiniuException
     * @return void
     * @throws
     * @Description: 七牛空间内文件重命名
     */
    public static void renameFile(String bucket, String key, String targetKey) throws QiniuException {
        bucketManager.rename(bucket, key, targetKey);
    }

    /**
     * @param bucket  空间名称
     * @param key     空间内文件的key[唯一的]
     * @param @throws QiniuException
     * @return void
     * @throws
     * @Description: 七牛空间内文件删除
     */
    public static void deleteFile(String bucket, String key) throws QiniuException {
        bucketManager.delete(bucket, key);
    }

    /**
     * @param @param  bucketName   空间名称
     * @param @param  prefix       文件key的前缀
     * @param @param  limit        批量提取的最大数目
     * @param @return
     * @param @throws QiniuException
     * @return FileInfo[]
     * @throws
     * @Description: 返回指定空间下的所有文件信息
     */
    public static FileInfo[] findFiles(String bucketName, String prefix, int limit) throws QiniuException {
        FileListing listing = bucketManager.listFiles(bucketName, prefix, null, limit, null);
        if (listing == null || listing.items == null || listing.items.length <= 0) {
            return null;
        }
        return listing.items;
    }

    /**
     * @param @param  bucketName   空间名称
     * @param @param  prefix       文件key的前缀
     * @param @return
     * @param @throws QiniuException
     * @return FileInfo[]
     * @throws
     * @Description: 返回指定空间下的所有文件信息
     */
    public static FileInfo[] findFiles(String bucketName, String prefix) throws QiniuException {
        FileListing listing = bucketManager.listFiles(bucketName, prefix, null, Integer.valueOf(LIMIT_SIZE), null);
        if (listing == null || listing.items == null || listing.items.length <= 0) {
            return null;
        }
        return listing.items;
    }

    /**
     * @param @param  bucketName
     * @param @param  key
     * @param @return
     * @param @throws QiniuException
     * @return FileInfo[]
     * @throws
     * @Description: 返回指定空间下的所有文件信息
     */
    public static FileInfo[] findFiles(String bucketName) throws QiniuException {
        FileListing listing = bucketManager.listFiles(bucketName, null, null, Integer.valueOf(LIMIT_SIZE), null);
        if (listing == null || listing.items == null || listing.items.length <= 0) {
            return null;
        }
        return listing.items;
    }

    /**
     * @param @param  bucketName
     * @param @param  key
     * @param @param  limit
     * @param @return
     * @param @throws QiniuException
     * @return FileInfo
     * @throws
     * @Description: 返回指定空间下的某个文件
     */
    public static FileInfo findOneFile(String bucketName, String key, int limit) throws QiniuException {
        FileListing listing = bucketManager.listFiles(bucketName, key, null, limit, null);
        if (listing == null || listing.items == null || listing.items.length <= 0) {
            return null;
        }
        return (listing.items)[0];
    }

    /**
     * @param @param  bucketName
     * @param @param  key
     * @param @return
     * @param @throws QiniuException
     * @return FileInfo
     * @throws
     * @Description: 返回指定空间下的某个文件(重载)
     */
    public static FileInfo findOneFile(String bucketName, String key) throws QiniuException {
        FileListing listing = bucketManager.listFiles(bucketName, key, null, Integer.valueOf(LIMIT_SIZE), null);
        if (listing == null || listing.items == null || listing.items.length <= 0) {
            return null;
        }
        return (listing.items)[0];
    }


    /**
     * 从 inputstream 中写入七牛
     *
     * @param key     文件名
     * @param content 要写入的内容
     * @return
     * @throws AuthException
     * @throws JSONException
     */
    public static String uploadFile(String key, String content) throws AuthException, JSONException {
        // 读取的时候按的二进制，所以这里要同一
        ByteArrayInputStream inputStream = new ByteArrayInputStream(content.getBytes());

//        String uptoken = getUpToken(QINIU_GOODS_BUCKET);
        String uptoken = getUpToken(yougoubao);

        // 可选的上传选项，具体说明请参见使用手册。
        PutExtra extra = new PutExtra();

        // 上传文件
        PutRet ret = IoApi.Put(uptoken, key, inputStream, extra);

        if (ret.ok()) {
            return ret.getResponse();
        } else {
            return null;
        }
    }

    //通过File上传
    public static String uploadFile(File file, QINIU_BUCKET_DOMAIN_ENUM bucket) throws Exception {
        String uptoken = getUpToken(bucket.getBucket());

        // 可选的上传选项，具体说明请参见使用手册。
        PutExtra extra = new PutExtra();

        // 上传文件
        PutRet ret = IoApi.putFile(uptoken, file.getName(), file.getAbsolutePath(), extra);

        if (ret.ok()) {
            return getFileUrl(ret.getKey(), bucket.getDomain());
        } else {
            return null;
        }
    }


    //获得下载地址
    public static String getDownloadFileUrl(String filename) throws Exception {
        String baseUrl = URLUtils.makeBaseUrl(QINIU_TEST_DOMAIN, filename);
        GetPolicy getPolicy = new GetPolicy();
        String downloadUrl = getPolicy.makeRequest(baseUrl, mac);
        return downloadUrl;
    }

    //获得圖片地址
    public static String getFileUrl(String filename, String domain) {
        String baseUrl = null;
        try {
            baseUrl = makeHttpBaseUrl(domain, filename);
        } catch (EncoderException e) {
            e.printStackTrace();
        }
        return baseUrl;
    }

    //获得圖片地址
    public static String getFileUrlAsHttps(String filename, String domain) {
        String baseUrl = null;
        try {
//            baseUrl = makeHttpsBaseUrl(domain, filename);
            baseUrl = makeHttpBaseUrl(domain, filename);
        } catch (EncoderException e) {
            e.printStackTrace();
        }
        return baseUrl;
    }

    //删除文件
    public static void deleteFile(String filename) {
        RSClient client = new RSClient(mac);
        client.delete(QINIU_TEST_DOMAIN, filename);
    }

    //获取凭证
    public static String getUpToken(String bucket) {
        return auth.uploadToken(bucket, null, 3600, new StringMap());
    }

    private Mac getMac() {
        Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
        return mac;
    }

    /**
     * @param @param  key
     * @param @return
     * @param @throws QiniuException
     * @return String
     * @throws
     * @Description: 返回七牛空间内指定文件的访问URL
     */
    public static String getFileAccessUrl(String key) throws QiniuException {
        return QINIU_TEST_DOMAIN + "/" + key;
    }

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    public static String upload(MultipartFile file, QINIU_BUCKET_DOMAIN_ENUM bucket) {
        try {
//            CommonsMultipartFile cf = (CommonsMultipartFile) file; //
//            DiskFileItem fi = (DiskFileItem) cf.getFileItem();
//            File localFile = fi.getStoreLocation();
            String millisecond = DateUtil.getCurrentMillisecond();
            File localFile = File.createTempFile("prefix", "_" + millisecond);
            file.transferTo(localFile);

            //如图片 >3M 压缩
            double size = file.getSize();
            float rate = (float) (1024 * 1000 * 1024 * 2 / size);
            if (rate < 1) {
                ImageUtils.reduceImg(localFile, localFile, 0, 0, rate);
            }
            Response map;
            if (localFile.exists()) {
                //调用put方法上传
//                ImageUtils.pressText(localFile.getAbsolutePath(), "LONG ZHI YOU", "宋体", Font.BOLD, 22, Color.WHITE, 0.3f);
                map = uploadManager.put(IOUtils.toByteArray(new FileInputStream(localFile)), null, getUpToken(bucket.getBucket()));
            } else {
                map = uploadManager.put(IOUtils.toByteArray(file.getInputStream()), null, getUpToken(bucket.getBucket()));
            }

            //清理临时文件
            //获取上传后 KEY 并且返回文件地址
            //或者 可以使用 com.lzy.common.constants/key 直接返回 减少服务请求
            if (bucket.bucket.equals(QINIU_BUCKET_DOMAIN_ENUM.ACTIVITY.bucket))
                return QiniuUtils.getFileUrlAsHttps(String.valueOf(map.jsonToMap().get("key")), bucket.getDomain());
            return QiniuUtils.getFileUrl(String.valueOf(map.jsonToMap().get("key")), bucket.getDomain());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        }
        return null;
    }

    /**
     * 流式上传
     *
     * @param inputStream
     * @param bucket
     * @return
     */
    public static String upload(InputStream inputStream, QINIU_BUCKET_DOMAIN_ENUM bucket) {
        try {
            //调用put方法上传
            Response map = uploadManager.put(IOUtils.toByteArray(inputStream), null, getUpToken(bucket.getBucket()));
            //获取上传后 KEY 并且返回文件地址
            //或者 可以使用 com.lzy.common.constants/key 直接返回 减少服务请求
            return QiniuUtils.getFileUrl(String.valueOf(map.jsonToMap().get("key")), bucket.getDomain());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        }
        return null;
    }

    public static String makeHttpsBaseUrl(String domain, String key) throws EncoderException {
        return HTTPS_TYPE + domain + "/" + URLEscape.escape(key);
    }

    public static String makeHttpBaseUrl(String domain, String key) throws EncoderException {
        return HTTP_TYPE + domain + "/" + URLEscape.escape(key);
    }


    public static String makeHttpsBaseUrl() {
        return HTTP_TYPE + QINIU_TEST_DOMAIN + "/";
    }

    public static String downloadRemote(String urlString, String filename)
            throws Exception {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        // 输入流
        InputStream is = con.getInputStream();
        String code = con.getHeaderField("Content-Encoding");
        System.out.println("cdoe:" + code);
        if ((null != code) && code.equals("gzip")) {
            GZIPInputStream gis = new GZIPInputStream(is);

            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            OutputStream os = new FileOutputStream(filename);
            // 开始读取
            while ((len = gis.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            gis.close();
            os.close();
            is.close();

        } else {

            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            OutputStream os = new FileOutputStream(filename);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            os.close();
            is.close();
        }
//        return uploadFile(new File(filename), QINIU_BUCKET_DOMAIN_ENUM.GOODS);
        return uploadFile(new File(filename), QINIU_BUCKET_DOMAIN_ENUM.yougoubao);
    }

    /**
     * 上传远程图片
     *
     * @param originalUrl 远程图片地址
     * @param bucket      要上传的bucket
     * @return
     * @throws IOException
     */
    public static String fetchImage(String originalUrl, QINIU_BUCKET_DOMAIN_ENUM bucket) throws IOException {
        String fix = parseSuffix(originalUrl);
        if (fix.equals("jpg"))
            fix = "bmp";
        URL url = new URL(originalUrl);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        BufferedImage image = ImageIO.read(connection.getInputStream());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, fix, os);
        InputStream is = new ByteArrayInputStream(os.toByteArray());
        int srcWidth = image.getWidth();      // 源图宽度
        int srcHeight = image.getHeight();    // 源图高度
        String path = QiniuUtils.upload(is, bucket);
        return path + "?" + srcWidth + "/" + srcHeight;
    }


    /**
     * 获取链接的后缀名
     *
     * @return
     */
    public static String parseSuffix(String url) {
        Pattern pattern = Pattern.compile("\\S*[?]\\S*");
        Matcher matcher = pattern.matcher(url);

        String[] spUrl = url.toString().split("/");
        int len = spUrl.length;
        String endUrl = spUrl[len - 1];

        if (matcher.find()) {
            String[] spEndUrl = endUrl.split("\\?");
            return spEndUrl[0].split("\\.")[1];
        }
        return endUrl.split("\\.")[1];
    }

    public static void main(String[] args) {
        try {
            String path = downloadRemote("http://img1.lzyhll.com/UploadFiles/i1/kindeditor/20151225/20151225213532_5085.jpg", "/20151225/20151225213532_5085.jpg");
            System.out.println("-----------------------------------------   " + path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
